_cached_apis = {}
import logging

from alipay import exceptions

logger = logging.getLogger(__name__)


def fundin(*args, **kwargs):
    print('fund_in')
def _get_api(gateway_ext):
    pid = gateway_ext.get('pid', None)
    if not pid:
        pid = gateway_ext.get('partner_id', None)
    alipay_key = gateway_ext.get('key', None)

    cachek_key = '{}-{}'.format(pid, alipay_key)

    if not cachek_key in _cached_apis:
        from alipay import Alipay
        api = Alipay(pid=pid, key=alipay_key, seller_id=pid)

        _cached_apis[cachek_key] = api
    else:
        api = _cached_apis[cachek_key]
    return api


def fundin(
        title,
        amount,
        config={},
        links={},
        *args,
        **kwargs):
    api = _get_api(config)
    trade_code = kwargs.get('trade_code', None)
    if not trade_code:
        import time
        trade_code = str(time.time())
    data = {
        'out_trade_no': trade_code,
        'subject': title,
        'total_fee': 0.01,  # request.amount,
        'body': title
    }
    if 'verify' in links:
        data.update({
            'return_url': links.get('verify')
        })
    if 'notify' in links:
        data.update({
            'notify_url': links.get('notify')
        })

    logger.info('Submit to alipay : %s', data)
    response = {}
    try:
        url = api.create_direct_pay_by_user_url(**data)

        logger.info('Payment[%s] created successfully. redirect url: %s', trade_code, url)
        response['success'] = True
        response['trade_code'] = trade_code

        response['credential'] = {
            'method': 'REDIRECT',
            'url': url
        }
        # response.approval_url.href = url
        # response.approval_url.method = 'REDIRECT'

    except exceptions.AlipayException as ae:
        logger.error(ae, exc_info=1)
        response['success'] = False
        response['result_message'] = ae
    return response


def verify(verify_data, config, *args, **kwargs):
    api = _get_api(config)
    logger.info("alipay verify param: {}".format(verify_data))

    success = api.verify_notify(**verify_data)
    response = {}
    response['success'] = success
    response['result_code'] = verify_data['trade_status']
    # response['result_message']

    extension = {
        'notify_id': verify_data.get('notify_id', None),
        'buyer_id': verify_data.get('buyer_id', None),
        'buyer_email': verify_data.get('buyer_email', None),
        'trade_no': verify_data.get('trade_no', None)
    }
    # response['notify_id']
    # response = VerifyResponse(success)
    # response.return_code = request.options.get('trade_status')
    # response.return_info = request.options
    # response.extension['notify_id'] = request.options.get('notify_id')
    # response.extension['buyer_id'] = request.options.get('buyer_id')
    # response.extension['buyer_email'] = request.options.get('buyer_email')
    # response.extension['trade_no'] = request.options.get('trade_no')
    response.setdefault('extension', extension)

    return response
